/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package eu.fastl.dragster.web.filter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * Default implementation of the Cache Key Generator using the plain URI + Query
 * String as cache key
 *
 * @author Ernst Fastl
 */
public class DefaultCacheKeyGeneratorImpl implements CacheKeyGenerator {

    public void register() {
        CacheKeyGeneratorProvider.setCacheKeyGenerator(this);
    }

    public Object createKey(ServletRequest request) {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            List<String> parameterList = new ArrayList<String>();
            Enumeration parameters = httpServletRequest.getParameterNames();
            while(parameters.hasMoreElements()) {
            	String parameterName = (String)parameters.nextElement();
            	parameterList.add(parameterName);
            }
            Collections.sort(parameterList);
            StringBuilder parameterKey = new StringBuilder();
            for (String name : parameterList) {
                parameterKey.append(name).append(httpServletRequest.getParameter(name));
            }
            StringBuilder retval = new StringBuilder(httpServletRequest.getRequestURI());
            retval.append(parameterKey);
            return retval.toString();
        } else {
            throw new UnsupportedOperationException(
                    "Default Key Generator Implementation only supports HttpServletRequests not: " + request.getClass());
        }
    }

}
